package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {


    private List<Map<String,String>> list=new ArrayList<>();
    private  AjaxController(){
        Map<String,String> map=new HashMap<>();//这个map中存储一些城市信息
        map.put("id", "100");
        map.put("city","beijing" );
        list.add(map);
        map=new HashMap<>();//这个map中存储一些城市信息
        map.put("id", "101");
        map.put("city","shanghai" );
        list.add(map);
    }

    @PutMapping("doAjaxPut")
    public  String doUpdateObject(@RequestParam Map<String,String> parammap){
        String id=parammap.get("id");
        Iterator<Map<String,String>> it=list.iterator();
        while (it.hasNext()){
            Map<String,String> map=it.next();
            if(map.get("id").equals(id)){
                map.put("city", parammap.get("city"));
            }
        }
        return "update ok";
    }

    @DeleteMapping("doAjaxDelete/{id}")
    public  String doDeleteObject(@PathVariable String id){

       /*for (Map<String,String> map:list) {
            if(map.get("id").equals(id)){
                list.remove(map); //这样删除会出现并发删除异常
            }
        }*/
        Iterator<Map<String,String>> it=list.iterator();
        while (it.hasNext()){
            Map<String,String> map=it.next();
            if(map.get("id").equals(id)){
                it.remove();//基于迭代器执行删除操作
            }
        }
        return "Delete ok";
    }

    @PostMapping("doAjaxPostJson")
    public String doSaveJsonObject(@RequestBody Map<String,String> map){
        list.add(map);
        return "save json ok";
    }

    //或用@RequestBody注解
    @PostMapping("doAjaxPost")
    public String doSaveObject(@RequestParam Map<String,String> map){
        list.add(map);
        return "save ok";
    }

   /* @RequestMapping("doAjaxGet")
    @ResponseBody
    public List<Map<String,String>> doAjaxGet(){
        return list;
    }*/
    @RequestMapping(path={"doAjaxGet/{city}","doAjaxGet"})
    @ResponseBody
    public List<Map<String,String>> doAjaxGet(@PathVariable(required = false) String city){
        if(city==null||"".equals(city))return list;
        List<Map<String,String>> queryResult=new ArrayList<>();//基于此集合存储查询结果
        for (Map<String,String> map:list) {
            if(map.get("city").contains(city)){
                queryResult.add(map);
            }
        }
        return queryResult;
    }

    @RequestMapping("/doAjaxStart")
    public String doAjaxStart(){
        try{Thread.sleep(3000);}catch (Exception e){}
        return "Response Result Of Ajax Get Request 01 ";
    }
}
